package com.dex4d.utils;

import android.content.Context;
import android.os.Environment;
import android.os.StatFs;
import android.text.TextUtils;

import com.framework.util.StringUtil;

import org.web3j.utils.Convert;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class BaseUtils {
    public static String UrlEncodeUnicode(final String s) {
        if (s == null) {
            return null;
        }
        final int length = s.length();
        final StringBuilder builder = new StringBuilder(length); // buffer
        for (int i = 0; i < length; i++) {
            final char ch = s.charAt(i);
            if ((ch & 0xff80) == 0) {
                if (BaseUtils.IsSafe(ch)) {
                    builder.append(ch);
                } else if (ch == ' ') {
                    builder.append('+');
                } else {
                    builder.append('%');
                    builder.append(BaseUtils.IntToHex((ch >> 4) & 15));
                    builder.append(BaseUtils.IntToHex(ch & 15));
                }
            } else {
                builder.append("%u");
                builder.append(BaseUtils.IntToHex((ch >> 12) & 15));
                builder.append(BaseUtils.IntToHex((ch >> 8) & 15));
                builder.append(BaseUtils.IntToHex((ch >> 4) & 15));
                builder.append(BaseUtils.IntToHex(ch & 15));
            }
        }
        return builder.toString();
    }

    static char IntToHex(final int n) {
        if (n <= 9) {
            return (char) (n + 0x30);
        }
        return (char) ((n - 10) + 0x61);
    }

    static boolean IsSafe(final char ch) {
        if ((((ch >= 'a') && (ch <= 'z')) || ((ch >= 'A') && (ch <= 'Z'))) || ((ch >= '0') && (ch <= '9'))) {
            return true;
        }
        switch (ch) {
            case '\'':
            case '(':
            case ')':
            case '*':
            case '-':
            case '.':
            case '_':
            case '!':
                return true;
        }
        return false;
    }

    // ----------------------------------------------------------------------------------------------------------------------------
    // MD5相关函数
    private static final char HEX_DIGITS[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd',
            'e', 'f'};

    /**
     * MD5运算
     *
     * @param s
     * @return String 返回密文
     */
    public static String getMd5(final String s) {
        try {
            // Create MD5 Hash
            final MessageDigest digest = MessageDigest.getInstance("MD5");
            digest.update(s.trim().getBytes());
            final byte messageDigest[] = digest.digest();
            return BaseUtils.toHexString(messageDigest);
        } catch (final NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return s;
    }

    /**
     * 转换为十六进制字符串
     *
     * @param b byte数组
     * @return String byte数组处理后字符串
     */
    public static String toHexString(final byte[] b) {// String to byte
        final StringBuilder sb = new StringBuilder(b.length * 2);
        for (final byte element : b) {
            sb.append(BaseUtils.HEX_DIGITS[(element & 0xf0) >>> 4]);
            sb.append(BaseUtils.HEX_DIGITS[element & 0x0f]);
        }
        return sb.toString();
    }

    /**
     * 检查是否安装了sd卡
     *
     * @return false 未安装
     */
    public static boolean sdcardMounted() {
        final String state = Environment.getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED) && !state.equals(Environment.MEDIA_MOUNTED_READ_ONLY)) {
            return true;
        }
        return false;
    }

    /**
     * 获取SD卡剩余空间的大小
     *
     * @return long SD卡剩余空间的大小（单位：byte）
     */
    public static long getSDSize() {
        final String str = Environment.getExternalStorageDirectory().getPath();
        final StatFs localStatFs = new StatFs(str);
        final long blockSize = localStatFs.getBlockSize();
        return localStatFs.getAvailableBlocks() * blockSize;
    }

    public static final void saveObject(String path, Object saveObject) {
        FileOutputStream fos = null;
        ObjectOutputStream oos = null;
        File f = new File(path);
        try {
            fos = new FileOutputStream(f);
            oos = new ObjectOutputStream(fos);
            oos.writeObject(saveObject);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (oos != null) {
                    oos.close();
                }
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static final Object restoreObject(String path) {
        FileInputStream fis = null;
        ObjectInputStream ois = null;
        Object object = null;
        File f = new File(path);
        if (!f.exists()) {
            return null;
        }
        try {
            fis = new FileInputStream(f);
            ois = new ObjectInputStream(fis);
            object = ois.readObject();
            return object;

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                if (ois != null) {
                    ois.close();
                }
                if (fis != null) {
                    fis.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return object;
    }

    public static void saveObject(Context context, String filename, Object object) {
        try {
            FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE);
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(object);
            oos.writeObject(null);
            oos.flush();
            oos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Object getObject(Context context, String filename) {
        try {
            FileInputStream fis = context.openFileInput(filename);
            ObjectInputStream ois = new ObjectInputStream(fis);
            return ois.readObject();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    //wei 单位转ether 单位，并且取小数点后6位
    public static String hexToEtherUnit(String hex){
        //String hex = "0x000000000000000000000000000000000000000000000000a688906bd8b00000";
        BigDecimal decimal = new BigDecimal(formatHexToDec(hex));
        return Convert.fromWei(decimal,Convert.Unit.ETHER).setScale(6,RoundingMode.DOWN).toString();
    }

    //十六进制转十进制
    public static String formatHexToDec(String hex){
        if(hex.equalsIgnoreCase("0x")){
            return "0";
        } else if(hex.length()>2 && hex.substring(0,2).equalsIgnoreCase("0x")){
            return new BigInteger(hex.substring(2), 16).toString();
        }else {
            return new BigInteger(hex, 16).toString();
        }
    }

    //格式化显示地址
    public static String formatAddress(String address){
        if(!StringUtil.isEmpty(address)){
            address = address.substring(0,8)+"..."+address.substring(address.length()-6,address.length());
        }
        return address;
    }

    //格式化Hash id
    public static String formatTxHash(String txHash){
        if(!StringUtil.isEmpty(txHash)){
            return txHash.substring(0, 12) + "..." + txHash.substring(txHash.length() - 10, txHash.length());
        }
        return txHash;
    }

    //获取6位数随机数字密码
    public static String getRandomPwd(){
        String random = System.currentTimeMillis()+"";
        return random.substring(random.length()-6,random.length());
    }

    public static long getTimeInMillis(String dateTime){
        Calendar calendar = Calendar.getInstance();
        try{
            calendar.setTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(dateTime));
        }catch (Exception e){
            return 0;
        }
        return calendar.getTimeInMillis();
    }

    /**
     * 获得世界协调时的近似值
     * @return  Date
     */
    public static Date getUTCTime() {
        Calendar cal = Calendar.getInstance();
        //获得时区和 GMT-0 的时间差,偏移量
        int offset = cal.get(Calendar.ZONE_OFFSET);
        //获得夏令时  时差
        int dstoff = cal.get(Calendar.DST_OFFSET);
        cal.add(Calendar.MILLISECOND, -(offset + dstoff));
        return cal.getTime();
    }

    public static String getCountdown(String dateTime){
        long endTime = BaseUtils.getTimeInMillis(dateTime);
        //long startTime = new Date().getTime();
        long startTime = getUTCTime().getTime();
        long midTime = (endTime-startTime)/1000;
        long hh = midTime / 60 / 60;
        long mm = midTime / 60 % 60;
        long ss = midTime % 60;
        return hh + ":"+mm + ":"+ss;
    }

    private static String replaceBlank(String s) {
        String result= null;
        if (s == null) {
            return result;
        } else {
            Pattern p = Pattern.compile("\\s|\t|\r|\n");
            Matcher m = p.matcher(s);
            result= m.replaceAll("*");
            return result;
        }
    }

    public static boolean isEthAddress(String s){
        if(!TextUtils.isEmpty(s)
                && s.length() == 42){
            return true;
        }else {
            return false;
        }
    }

    public static String formatTime(String time) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(Long.parseLong(time)* 1000L);
        return sdf.format(calendar.getTime());
    }

    public static void main(String[] args){
//        try {
//            System.out.println(Arith.div(10,100,2));
//        }catch (Exception e){}
//        String ss = "shoot      head you host speed victory cover embark donor smile raise brave";
//
//        StringBuffer sb = new StringBuffer();
//        for(char c: ss.toCharArray()){
//            if((c>=97 && c<=122) || (c>=65 && c<=90)){
//                sb.append(c);
//            }else {
//                sb.append(" ");
//            }
//        }
//        ss = sb.toString();
//
//        String[] arrays = ss.split("\\s+");
//        for(String s:arrays)
//        {
//            System.out.println(s);
//        }
//
//        List<String> list  = Arrays.asList(arrays);
//        StringBuffer sb2 = new StringBuffer();
//        for(String str:list){
//            sb2.append(str).append(" ");
//        }
//
//        System.out.println(sb2.toString().trim());

        System.out.println(formatTime("1543977267"));
    }
}
